# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
from ui_login import Ui_Login

import sys
sys.path.append('../')

from database.userUtils import login
from MySQLdb import OperationalError

class LoginDialog(QtGui.QDialog):

	def __init__(self):
		QtGui.QDialog.__init__(self)

		# Set up the user interface from Designer.
		self.ui = Ui_Login()
		self.ui.setupUi(self)


		self.ui.usernameEdit.hide()
		self.ui.passwordEdit.hide()
		self.ui.usernameLabel.hide()
		self.ui.passwordLabel.hide()

		self.connect(self.ui.loginButton, QtCore.SIGNAL("clicked()"), self.loginAction)
		self.connect(self.ui.writeCheckBox, QtCore.SIGNAL("clicked()"), self.writeCheck)

	def loginAction(self):

		if self.ui.writeCheckBox.isChecked():
			username = str(self.ui.usernameEdit.text())
			password = str(self.ui.passwordEdit.text())
		else:
			username = ''
			password = ''

		host = str(self.ui.databaseHostLineEdit.text())
		db = str(self.ui.databaseNameLineEdit.text())

		try:
			login(db, host, username, password)
		except ValueError:
			self.dialog = QtGui.QMessageBox(QtGui.QMessageBox.Critical, "Error", "Wrong username or password!", QtGui.QMessageBox.Ok)
			self.dialog.show()
			return
		except OperationalError:
			self.dialog = QtGui.QMessageBox(QtGui.QMessageBox.Critical, "Error", "Error connecting to the database", QtGui.QMessageBox.Ok)
			self.dialog.show()
			return

		self.dialog = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Logged in", "Logged in", QtGui.QMessageBox.Ok)
		self.dialog.show()

		self.close()

	def writeCheck(self):
		if self.ui.writeCheckBox.isChecked():
			self.ui.usernameEdit.show()
			self.ui.passwordEdit.show()
			self.ui.usernameLabel.show()
			self.ui.passwordLabel.show()
		else:
			self.ui.usernameEdit.hide()
			self.ui.passwordEdit.hide()
			self.ui.usernameLabel.hide()
			self.ui.passwordLabel.hide()
